<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>创世熔炉 - 无限融合工坊</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    body {
      background: linear-gradient(135deg, #fff7ed 0%, #fef3c7 100%);
      font-family: 'HarmonyOS Sans', '微软雅黑', Arial, sans-serif;
      margin: 0; padding: 0; color: #4b3f1d; min-height: 100vh; transition: background 0.4s;
      overflow-x: hidden;
    }
    .dynamic-bg {
      position: fixed; left: 0; top: 0; width: 100vw; height: 100vh; z-index: 0;
      pointer-events: none; background: radial-gradient(circle at 60% 40%, #fbbf24 0%, #fef3c7 100%);
      animation: bgflow 12s linear infinite alternate;
    }
    @keyframes bgflow {
      0% { background-position: 60% 40%; }
      100% { background-position: 40% 60%; }
    }
    .container { max-width: 600px; margin: 0 auto; padding: 28px 8px 100px 8px; position: relative; z-index: 1;}
    .header { text-align: center; margin-bottom: 20px; }
    .header-logo { width: 70px; height: 70px; margin: 0 auto 10px; border-radius: 20px;
      background: linear-gradient(135deg, #f97316, #fdba74); display: flex; align-items: center; justify-content: center;
      font-size: 2.5rem; color: #fff; box-shadow: 0 4px 16px #f59e0b33; position: relative; overflow: hidden;}
    .flame { position: absolute; bottom: 0; left: 50%; transform: translateX(-50%); width: 32px; height: 44px; z-index: 2;}
    .flame-shape { position: absolute; width: 32px; height: 44px; background: radial-gradient(circle at 50% 80%, #fde68a 60%, #f59e0b 80%, #ef4444 100%);
      border-radius: 50% 50% 40% 40%; animation: flameAnim 1.2s infinite alternate;}
    @keyframes flameAnim { 0% {height: 44px;} 50% {height: 54px;} 100% {height: 44px;} }
    .header h1 { font-size: 2.3rem; color: #f97316; font-weight: bold; margin-bottom: 4px; letter-spacing: 2px; text-shadow: 0 2px 8px #fbbf2433;}
    .header .slogan { color: #f59e0b; font-size: 1.13rem; margin-bottom: 10px; font-weight: 600;}
    .feature-combo { display: flex; justify-content: space-between; gap: 10px; margin-bottom: 20px;}
    .feature-item { flex: 1; background: #fff7ed; border-radius: 16px; padding: 12px 0 8px 0; text-align: center; font-size: 1.05rem; color: #f97316;
      display: flex; flex-direction: column; align-items: center; box-shadow: 0 2px 8px #fde68a55;}
    .feature-item i { font-size: 1.4rem; margin-bottom: 2px; color: #fdba74;}
    .progress-bar-wrap { margin: 0 0 18px 0; }
    .progress-bar-label { font-size: 1rem; color: #b45309; margin-bottom: 4px; }
    .progress-bar { width: 100%; height: 14px; background: #fde68a; border-radius: 8px; overflow: hidden; }
    .progress-bar-inner { height: 100%; background: linear-gradient(90deg, #f97316, #fdba74); border-radius: 8px; transition: width 0.6s;}
    .progress-bar-text { text-align: right; font-size: 0.98rem; color: #f97316; margin-top: 2px;}
    .card { background: white; border-radius: 24px; box-shadow: 0 4px 18px rgba(249,115,22,0.08); margin-bottom: 28px; padding: 26px 20px 22px 20px; position: relative; overflow: hidden; transition: box-shadow 0.2s, transform 0.2s;}
    .card:hover { box-shadow: 0 8px 32px #fbbf2433; transform: translateY(-2px) scale(1.01);}
    .card-title { font-size: 1.25rem; font-weight: bold; color: #f97316; margin-bottom: 14px; display: flex; align-items: center; gap: 10px; letter-spacing: 1px;}
    .card-desc { color: #b45309; font-size: 1.05rem; margin-bottom: 12px;}
    /* 元素合成区 */
    .element-lab { display: flex; align-items: center; justify-content: center; gap: 14px; margin-bottom: 12px; flex-wrap: wrap;}
    .element-btn { width: 56px; height: 56px; border-radius: 18px; background: #fef3c7; border: 2px solid #fbbf24; font-size: 2.2rem; display: flex; align-items: center; justify-content: center; cursor: pointer; margin: 2px 0; transition: background 0.2s, transform 0.1s, box-shadow 0.2s; box-shadow: 0 2px 8px #fde68a33;}
    .element-btn:active, .element-btn.active { transform: scale(0.93); background: #fde68a; box-shadow: 0 4px 16px #fbbf2433; border-color: #f59e0b;}
    .element-eq { font-size: 1.6rem; color: #f59e0b; margin: 0 4px;}
    .element-result { font-size: 2.3rem; margin-left: 12px; transition: opacity 0.3s; opacity: 1; font-weight: bold; color: #f97316; text-shadow: 0 2px 8px #fbbf2433;}
    .element-formula { color: #f59e0b; font-size: 1.13rem; margin-top: 10px; text-align: center; font-weight: 600;}
    .element-hint { color: #b45309; font-size: 1.01rem; margin-top: 6px; text-align: center;}
    .element-history { margin: 12px 0 0 0; font-size: 1.01rem; color: #b45309; text-align: center;}
    .element-random, .element-challenge { background: #fde68a; color: #b45309; border: none; border-radius: 14px; padding: 7px 20px; font-size: 1.05rem; font-weight: 600; cursor: pointer; margin: 12px 8px 0 0; display: inline-block; box-shadow: 0 2px 8px #fde68a44; transition: background 0.2s;}
    .element-random:active, .element-challenge:active { background: #fbbf24; }
    .element-challenge { background: #fdba74; color: #fff; }
    .element-challenge:active { background: #f97316; }
    .element-collection { margin: 10px 0 0 0; font-size: 0.98rem; color: #f97316; text-align: center;}
    .element-new { display: inline-block; background: #fbbf24; color: #fff; border-radius: 10px; padding: 2px 10px; font-size: 0.9rem; margin-left: 8px; animation: pop 0.7s;}
    @keyframes pop { 0% {transform: scale(0.7);} 60% {transform: scale(1.2);} 100% {transform: scale(1);} }
    .achievement-popup { position: fixed; left: 50%; top: 18%; transform: translate(-50%,0); background: #fffbe6; color: #f97316; border-radius: 18px; box-shadow: 0 8px 32px #fbbf2433; padding: 28px 36px; font-size: 1.2rem; font-weight: bold; z-index: 999; display: none; animation: fadeIn 0.7s;}
    @keyframes fadeIn { 0% {opacity: 0; transform: translate(-50%,-30px);} 100% {opacity: 1; transform: translate(-50%,0);} }
    /* 光影涂鸦区 */
    .graffiti-area { background: #fef3c7; border-radius: 20px; margin: 14px 0 0 0; overflow: hidden; position: relative; box-shadow: 0 2px 8px #fde68a55; padding-top: 0; }
    .graffiti-canvas { width: 100%; height: 160px; display: block; background: #fff7ed; touch-action: none; cursor: crosshair; border-radius: 14px; margin-top: 0; }
    .graffiti-tip { position: absolute; left: 14px; top: 10px; color: #f59e0b; font-size: 1.01rem; pointer-events: none; opacity: 0.7;}
    .graffiti-tools {
      display: flex; flex-wrap: nowrap; overflow-x: auto; gap: 8px; padding: 6px 0 6px 0; background: #fff7ed; border-radius: 12px 12px 0 0; position: relative; z-index: 2;
      scrollbar-width: thin; scrollbar-color: #fde68a #fff7ed;
    }
    .graffiti-tools::-webkit-scrollbar { height: 6px; background: #fff7ed; }
    .graffiti-tools::-webkit-scrollbar-thumb { background: #fde68a; border-radius: 6px; }
    .graffiti-tool { min-width: 60px; font-size: 1rem; margin: 0 2px; white-space: nowrap; }
    @media (max-width: 600px) {
      .graffiti-tool { min-width: 44px; font-size: 0.85rem; padding: 4px 6px; }
      .graffiti-tools { gap: 4px; }
    }
    .tools-scroll { overflow-x: auto; }
    .graffiti-area { padding-top: 0; }
    .graffiti-canvas { margin-top: 0; }
    /* 粒子实验区 */
    .particle-area { background: #fef3c7; border-radius: 20px; margin: 14px 0 0 0; overflow: hidden; position: relative; box-shadow: 0 2px 8px #fde68a55; padding-bottom: 10px;}
    .particle-canvas { width: 100%; height: 160px; display: block; background: #fff7ed; cursor: pointer; border-radius: 14px;}
    .particle-controls {
      display: flex; flex-direction: column; gap: 6px; margin: 18px 0 0 0; padding: 0 2px;
      overflow-x: auto; scrollbar-width: thin; scrollbar-color: #fde68a #fef3c7;
    }
    .controls-scroll { overflow-x: auto; }
    .particle-btn-row { display: flex; flex-wrap: nowrap; gap: 8px; overflow-x: auto; }
    .particle-slider-row { display: flex; flex-wrap: nowrap; gap: 8px; align-items: center; overflow-x: auto; margin-top: 4px; }
    .particle-btn { min-width: 60px; font-size: 1rem; white-space: nowrap; }
    .particle-slider { width: 100px; min-width: 60px; }
    @media (max-width: 600px) {
      .particle-btn { min-width: 44px; font-size: 0.85rem; padding: 4px 6px; }
      .particle-btn-row, .particle-slider-row { gap: 4px; }
      .particle-slider { width: 60px; }
    }
    .furnace-tip { margin: 36px 0 0 0; padding: 18px 20px; background: #fef3c7; color: #b45309; border-radius: 18px; font-size: 1.07rem; text-align: center; box-shadow: 0 2px 8px #fde68a44;}
    .footer-btn { margin: 40px auto 0 auto; display: block; background: linear-gradient(90deg, #f97316, #fdba74); color: #fff; border: none; border-radius: 22px; font-size: 1.18rem; font-weight: 600; padding: 15px 48px; box-shadow: 0 4px 16px #f59e0b33; cursor: pointer; transition: background 0.2s, transform 0.1s;}
    .footer-btn:active { transform: scale(0.97);}
    @media (max-width: 600px) {
      .container { padding: 10px 2px 80px 2px;}
      .header-logo { width: 48px; height: 48px; font-size: 1.7rem;}
      .header h1 { font-size: 1.4rem;}
      .feature-item { font-size: 0.9rem;}
    }
  </style>
</head>
<body>
  <div class="dynamic-bg"></div>
  <div class="container">
    <div class="header">
      <div class="header-logo">
        <i class="fas fa-fire"></i>
        <div class="flame"><div class="flame-shape"></div></div>
      </div>
      <h1>创世熔炉</h1>
      <div class="slogan">无限融合工坊 · 元素合成 · 光影涂鸦 · 粒子沙盒</div>
    </div>
    <div class="feature-combo">
      <div class="feature-item"><i class="fas fa-flask"></i>元素融合</div>
      <div class="feature-item"><i class="fas fa-pen-nib"></i>光影涂鸦</div>
      <div class="feature-item"><i class="fas fa-atom"></i>粒子沙盒</div>
    </div>
    <div class="progress-bar-wrap">
      <div class="progress-bar-label">探索进度</div>
      <div class="progress-bar"><div class="progress-bar-inner" id="progressBarInner" style="width:0%"></div></div>
      <div class="progress-bar-text" id="progressBarText">已发现 0/128 公式，成就 0/8，彩蛋 0/12</div>
    </div>

    <!-- 元素合成区 -->
    <div class="card" id="fusionCard">
      <div class="card-title"><i class="fas fa-flask"></i> 元素融合</div>
      <div class="card-desc">点击/拖拽组合主元素，探索隐藏公式，解锁成就与彩蛋</div>
      <div class="element-lab" id="elementLab"></div>
      <div style="text-align:center;margin:14px 0;">
        <span class="element-eq" id="eleA">?</span>
        <span class="element-eq">+</span>
        <span class="element-eq" id="eleB">?</span>
        <span class="element-eq">=</span>
        <span class="element-result" id="eleResult">?</span>
      </div>
      <div class="element-formula" id="eleFormula">请选择两个元素进行合成</div>
      <div class="element-hint" id="elementHint">示例：🔥+💧=☁️ 蒸汽，☁️+🌪️=⛈️ 风暴，更多彩蛋等你发现！</div>
      <button class="element-random" id="randomCombineBtn">随机合成</button>
      <button class="element-challenge" id="challengeBtn">每日挑战</button>
      <button class="element-random" id="aiSuggestBtn">AI智能推荐</button>
      <div class="element-history" id="elementHistory"></div>
      <div class="element-collection" id="elementCollection"></div>
    </div>

    <!-- 成就弹窗 -->
    <div class="achievement-popup" id="achievementPopup"></div>

    <!-- 光影涂鸦区 -->
    <div class="card">
      <div class="card-title"><i class="fas fa-pen-nib"></i> 光影涂鸦</div>
      <div class="card-desc">多色笔刷、粒子特效、AI生成、撤销/重做/保存/分享</div>
      <div class="graffiti-area">
        <div class="graffiti-tools tools-scroll">
          <input type="text" id="aiPrompt" placeholder="输入关键词让AI帮你画..." class="graffiti-tool" style="width:120px;">
          <button class="graffiti-tool" data-brush="rainbow">彩虹笔</button>
          <button class="graffiti-tool" data-brush="glow">荧光笔</button>
          <button class="graffiti-tool" data-brush="fire">火焰笔</button>
          <button class="graffiti-tool" data-brush="star">星光笔</button>
          <button class="graffiti-tool" data-brush="wave">波浪笔</button>
          <button class="graffiti-tool" id="aiGenBtn">AI生成</button>
          <button class="graffiti-tool" id="undoGraffitiBtn">撤销</button>
          <button class="graffiti-tool" id="redoGraffitiBtn">重做</button>
          <button class="graffiti-tool" id="saveGraffitiBtn">保存</button>
          <button class="graffiti-tool" id="shareGraffitiBtn">分享</button>
          <button class="graffiti-tool" id="clearGraffitiBtn">清空</button>
        </div>
        <canvas class="graffiti-canvas" id="graffitiCanvas"></canvas>
        <div class="graffiti-tip">在此区域滑动绘制光轨</div>
      </div>
    </div>

    <!-- 粒子沙盒区 -->
    <div class="card">
      <div class="card-title"><i class="fas fa-atom"></i> 粒子沙盒</div>
      <div class="card-desc">多物理模式、粒子自定义、互动玩法、成就解锁</div>
      <div class="particle-area">
        <canvas class="particle-canvas" id="particleCanvas"></canvas>
        <div class="particle-controls controls-scroll">
          <div class="particle-btn-row">
            <button class="particle-btn" id="gravityBtn">引力</button>
            <button class="particle-btn" id="repelBtn">斥力</button>
            <button class="particle-btn" id="elasticBtn">弹性</button>
            <button class="particle-btn" id="attractBtn">吸附</button>
            <button class="particle-btn" id="explodeBtn">爆炸</button>
            <button class="particle-btn" id="resetParticleBtn">重置</button>
            <button class="particle-btn" id="springBtn">弹簧链</button>
            <button class="particle-btn" id="blackholeBtn">黑洞</button>
          </div>
          <div class="particle-slider-row">
            <input type="range" min="6" max="48" value="18" class="particle-slider" id="particleCountSlider">
            <span id="particleCountLabel">18粒子</span>
            <input type="range" min="4" max="32" value="8" class="particle-slider" id="particleSizeSlider">
            <span id="particleSizeLabel">8像素</span>
            <input type="range" min="1" max="10" value="3" class="particle-slider" id="particleMassSlider">
            <span id="particleMassLabel">质量3</span>
          </div>
        </div>
        <button class="particle-btn" id="aiParticleBtn" style="margin:10px auto 0 auto;display:block;">AI物理</button>
      </div>
    </div>

    <div class="furnace-tip">
      <b>鸿蒙特性：</b> 多卡片聚合、实时动效刷新、服务免安装拉起
      <br><b>彩蛋提示：</b> 发现全部隐藏公式、成就与彩蛋，解锁专属称号和祝福！
    </div>
    <button class="footer-btn" onclick="window.location.href='index.html'"><i class="fas fa-home"></i> 返回首页</button>
  </div>
  <button id="aiHelperBtn" style="position:fixed;right:24px;bottom:24px;z-index:999;background:#fbbf24;color:#fff;border:none;border-radius:50%;width:54px;height:54px;font-size:2rem;box-shadow:0 4px 16px #f59e0b33;cursor:pointer;">🤖</button>
  <script>
    // ====== 元素融合数据与逻辑 ======
    const allElements = [
      { key: 'fire', emoji: '🔥', name: '火' },
      { key: 'water', emoji: '💧', name: '水' },
      { key: 'wind', emoji: '🌪️', name: '风' },
      { key: 'cloud', emoji: '☁️', name: '云' },
      { key: 'light', emoji: '💡', name: '光' },
      { key: 'earth', emoji: '🌱', name: '土' },
      { key: 'ice', emoji: '❄️', name: '冰' },
      { key: 'bolt', emoji: '⚡', name: '电' },
      { key: 'egg', emoji: '🥚', name: '蛋' },
      { key: 'star', emoji: '⭐', name: '星' },
      { key: 'rain', emoji: '🌧️', name: '雨' },
      { key: 'mystery', emoji: '❓', name: '谜' }
    ];
    // 生成主按钮
    const elementLab = document.getElementById('elementLab');
    allElements.forEach(ele => {
      const btn = document.createElement('div');
      btn.className = 'element-btn';
      btn.dataset.ele = ele.key;
      btn.title = ele.name;
      btn.innerText = ele.emoji;
      elementLab.appendChild(btn);
    });

    // 公式库（部分特殊+自动生成隐藏）
    const formulas = {
      'fire+water': {result:'☁️',desc:'蒸汽',egg:true},
      'cloud+wind': {result:'⛈️',desc:'风暴',egg:true},
      'fire+earth': {result:'熔岩',desc:'火山喷发',egg:true},
      'water+ice': {result:'雪',desc:'降雪',egg:true},
      'light+star': {result:'✨',desc:'星辉',egg:true},
      'egg+star': {result:'🐣',desc:'星之生命',egg:true},
      'egg+fire': {result:'🐉',desc:'龙之诞生',egg:true},
      'light+cloud': {result:'🌈',desc:'彩虹',egg:true},
      'rain+earth': {result:'🌻',desc:'花开',egg:true},
      'fire+ice': {result:'水',desc:'极端反应',egg:true},
      'bolt+cloud': {result:'⚡',desc:'雷暴',egg:true},
      'mystery+star': {result:'🪐',desc:'宇宙奥秘',egg:true}
    };
    // 自动生成隐藏公式
    let totalFormulas = 0, foundFormulas = 0, foundEggs = 0, foundAchievements = 0, foundEggKeys = {};
    for(let i=0;i<allElements.length;i++){
      for(let j=0;j<allElements.length;j++){
        if(i!==j){
          let key = allElements[i].key+'+'+allElements[j].key;
          if(!formulas[key]){
            formulas[key] = {result:allElements[(i+j)%allElements.length].emoji,desc:'隐藏彩蛋'};
          }
          totalFormulas++;
        }
      }
    }
    // 合成历史与图鉴
    let eleA = null, eleB = null;
    let history = [];
    let collection = {};
    let challengeKey = null;
    let challengeDone = false;
    // 进度条
    function updateProgress() {
      foundFormulas = Object.keys(collection).length;
      foundEggs = Object.values(collection).filter(v=>v.egg).length;
      foundAchievements = Object.values(collection).filter(v=>v.achieve).length;
      document.getElementById('progressBarInner').style.width = (foundFormulas/totalFormulas*100).toFixed(1)+'%';
      document.getElementById('progressBarText').textContent = `已发现 ${foundFormulas}/${totalFormulas} 公式，成就 ${foundAchievements}/8，彩蛋 ${foundEggs}/12`;
    }
    // 合成操作
    document.querySelectorAll('.element-btn').forEach(btn => {
      btn.onclick = function() {
        if(!eleA) {
          eleA = this.dataset.ele;
          document.getElementById('eleA').textContent = this.textContent;
          this.classList.add('active');
        } else if(!eleB) {
          eleB = this.dataset.ele;
          document.getElementById('eleB').textContent = this.textContent;
          this.classList.add('active');
          showFormula();
        } else {
          eleA = this.dataset.ele; eleB = null;
          document.getElementById('eleA').textContent = this.textContent;
          document.getElementById('eleB').textContent = '?';
          document.getElementById('eleResult').textContent = '?';
          document.getElementById('eleFormula').textContent = '请选择两个元素进行合成';
          document.querySelectorAll('.element-btn').forEach(b=>b.classList.remove('active'));
          this.classList.add('active');
        }
      }
    });
    function showFormula() {
      let key = eleA+'+'+eleB;
      let f = formulas[key];
      if(f) {
        document.getElementById('eleResult').textContent = f.result;
        document.getElementById('eleFormula').textContent = `${document.getElementById('eleA').textContent} + ${document.getElementById('eleB').textContent} = ${f.result}（${f.desc}）`;
        history.unshift(`${document.getElementById('eleA').textContent}+${document.getElementById('eleB').textContent}→${f.result}`);
        if(history.length>10) history.length=10;
        document.getElementById('elementHistory').textContent = '历史：' + history.join('，');
        // 新发现动画
        if(!collection[key]) {
          collection[key] = {result:f.result,desc:f.desc,egg:!!f.egg};
          document.getElementById('elementCollection').innerHTML = `<span class=\"element-new\">新发现！已解锁${foundFormulas+1}种</span>`;
          setTimeout(()=>{document.getElementById('elementCollection').innerHTML='';}, 1800);
          if(f.egg && !foundEggKeys[key]) {
            foundEggKeys[key] = true;
            showAchievement(`彩蛋发现：${document.getElementById('eleA').textContent}+${document.getElementById('eleB').textContent}→${f.result}！`);
          }
          // 特殊成就
          if(key==='egg+fire') showAchievement('成就：龙之诞生！');
          if(key==='light+cloud') showAchievement('成就：发现彩虹！');
          if(key==='rain+earth') showAchievement('成就：花开大地！');
          if(key==='mystery+star') showAchievement('成就：宇宙奥秘！');
        }
        updateProgress();
        // 合成动画
        document.getElementById('eleResult').style.opacity = 0.2;
        setTimeout(()=>{document.getElementById('eleResult').style.opacity=1;},200);
        // 挑战检测
        if(key===challengeKey && !challengeDone) {
          challengeDone = true;
          showAchievement('每日挑战完成！');
        }
      } else {
        document.getElementById('eleResult').textContent = '❓';
        document.getElementById('eleFormula').textContent = '未知公式，快去发现新组合！';
        document.getElementById('elementHistory').textContent = '历史：' + history.join('，');
        document.getElementById('eleResult').style.opacity = 0.2;
        setTimeout(()=>{document.getElementById('eleResult').style.opacity=1;},200);
      }
      document.querySelectorAll('.element-btn').forEach(b=>b.classList.remove('active'));
    }
    document.getElementById('randomCombineBtn').onclick = function() {
      let btns = Array.from(document.querySelectorAll('.element-btn'));
      let a = btns[Math.floor(Math.random()*btns.length)];
      let b = btns[Math.floor(Math.random()*btns.length)];
      while(b===a) b = btns[Math.floor(Math.random()*btns.length)];
      a.click(); setTimeout(()=>b.click(), 200);
    };
    // 每日挑战
    function setChallenge() {
      let keys = Object.keys(formulas);
      challengeKey = keys[Math.floor(Math.random()*keys.length)];
      challengeDone = false;
      let [a,b] = challengeKey.split('+');
      let aObj = allElements.find(e=>e.key===a), bObj = allElements.find(e=>e.key===b);
      document.getElementById('challengeBtn').textContent = `每日挑战：${aObj.emoji}+${bObj.emoji}`;
    }
    document.getElementById('challengeBtn').onclick = function() {
      if(challengeDone) {
        showAchievement('今日挑战已完成！');
      } else {
        let [a,b] = challengeKey.split('+');
        let aBtn = Array.from(document.querySelectorAll('.element-btn')).find(btn=>btn.dataset.ele===a);
        let bBtn = Array.from(document.querySelectorAll('.element-btn')).find(btn=>btn.dataset.ele===b);
        aBtn.click(); setTimeout(()=>bBtn.click(), 200);
      }
    };
    // 成就弹窗
    function showAchievement(msg) {
      let popup = document.getElementById('achievementPopup');
      popup.textContent = msg;
      popup.style.display = 'block';
      setTimeout(()=>{popup.style.display='none';}, 2200);
    }
    // 初始化
    setChallenge();
    updateProgress();

    // ====== 光影涂鸦 ======
    const graffiti = document.getElementById('graffitiCanvas');
    const gctx = graffiti.getContext('2d');
    let drawing = false, last = null, graffitiHistory = [], graffitiStep = -1;
    let brushType = 'rainbow';
    let bgAngle = 0;
    graffiti.width = graffiti.offsetWidth; graffiti.height = graffiti.offsetHeight;
    graffiti.addEventListener('pointerdown', e => { drawing=true; last=getPos(e); saveGraffitiStep(); });
    graffiti.addEventListener('pointermove', e => {
      if(!drawing) return;
      let now = getPos(e);
      let speed = Math.sqrt(Math.pow(now.x-last.x,2)+Math.pow(now.y-last.y,2));
      let color = getBrushColor(now, speed, brushType);
      gctx.strokeStyle = color;
      gctx.lineWidth = Math.max(2,Math.min(12,speed*1.7));
      gctx.beginPath();
      gctx.moveTo(last.x,last.y);
      gctx.lineTo(now.x,now.y);
      gctx.shadowColor = color;
      gctx.shadowBlur = brushType==='glow'?18:brushType==='fire'?8:12;
      // 星光笔特效
      if(brushType==='star'){
        for(let i=0;i<2;i++){
          let px = now.x+Math.random()*12-6, py = now.y+Math.random()*12-6;
          gctx.save();
          gctx.translate(px, py);
          gctx.rotate(Math.random()*Math.PI);
          gctx.globalAlpha = 0.7;
          gctx.beginPath();
          for(let j=0;j<5;j++){
            gctx.lineTo(Math.cos((18+j*72)/180*Math.PI)*6, -Math.sin((18+j*72)/180*Math.PI)*6);
            gctx.lineTo(Math.cos((54+j*72)/180*Math.PI)*2.5, -Math.sin((54+j*72)/180*Math.PI)*2.5);
          }
          gctx.closePath();
          gctx.fillStyle = '#fffbe6';
          gctx.shadowColor = '#fbbf24';
          gctx.shadowBlur = 8;
          gctx.fill();
          gctx.restore();
        }
      }
      // 波浪笔特效
      if(brushType==='wave'){
        gctx.save();
        gctx.strokeStyle = getBrushColor(now, speed, 'wave');
        gctx.lineWidth = 6;
        gctx.beginPath();
        for(let t=0;t<=1;t+=0.1){
          let x = last.x + (now.x-last.x)*t;
          let y = last.y + (now.y-last.y)*t + Math.sin(Date.now()/100+t*10)*8;
          if(t===0) gctx.moveTo(x,y);
          else gctx.lineTo(x,y);
        }
        gctx.stroke();
        gctx.restore();
      } else {
        gctx.stroke();
      }
      gctx.shadowBlur = 0;
      // 粒子特效
      if(brushType==='fire'||brushType==='rainbow') drawParticles(now.x,now.y,color);
      last = now;
      // 画布背景渐变随绘制动态变化
      bgAngle = (bgAngle+2)%360;
      document.body.style.background = `linear-gradient(${bgAngle}deg, #fff7ed 0%, #fef3c7 100%)`;
    });
    graffiti.addEventListener('pointerup', ()=>{drawing=false;last=null; saveGraffitiStep();});
    graffiti.addEventListener('pointerleave', ()=>{drawing=false;last=null;});
    function getPos(e) {
      const rect = graffiti.getBoundingClientRect();
      return {x: e.clientX-rect.left, y: e.clientY-rect.top};
    }
    // 多色笔刷切换
    document.querySelectorAll('.graffiti-tool[data-brush]').forEach(btn=>{
      btn.onclick = function(){
        document.querySelectorAll('.graffiti-tool[data-brush]').forEach(b=>b.classList.remove('active'));
        this.classList.add('active');
        brushType = this.dataset.brush;
      }
    });
    // AI生成
    document.getElementById('aiGenBtn').onclick = function() {
      const prompt = document.getElementById('aiPrompt').value.trim();
      if (prompt) {
        showAchievement('AI根据 "' + prompt + '" 生成了画作！');
        gctx.clearRect(0,0,graffiti.width,graffiti.height);
        for(let i=0;i<16;i++){
          let x1 = Math.random()*graffiti.width, y1 = Math.random()*graffiti.height;
          let x2 = Math.random()*graffiti.width, y2 = Math.random()*graffiti.height;
          let color = getBrushColor({x:x1,y:y1}, Math.random()*8+2, brushType);
          gctx.strokeStyle = color;
          gctx.lineWidth = Math.random()*8+2;
          gctx.beginPath();
          gctx.moveTo(x1,y1);
          gctx.lineTo(x2,y2);
          gctx.shadowColor = color;
          gctx.shadowBlur = 12;
          gctx.stroke();
          gctx.shadowBlur = 0;
        }
        saveGraffitiStep();
      } else {
        showAchievement('请输入关键词后再点击AI生成！');
      }
    };
    // 撤销/重做/保存/清空/分享
    document.getElementById('undoGraffitiBtn').onclick = function() {
      if(graffitiStep>0){
        graffitiStep--;
        let img = new window.Image();
        img.onload = function(){
          gctx.clearRect(0,0,graffiti.width,graffiti.height);
          gctx.drawImage(img,0,0);
        };
        img.src = graffitiHistory[graffitiStep];
      }
    };
    document.getElementById('redoGraffitiBtn').onclick = function() {
      if(graffitiStep<graffitiHistory.length-1){
        graffitiStep++;
        let img = new window.Image();
        img.onload = function(){
          gctx.clearRect(0,0,graffiti.width,graffiti.height);
          gctx.drawImage(img,0,0);
        };
        img.src = graffitiHistory[graffitiStep];
      }
    };
    document.getElementById('saveGraffitiBtn').onclick = function() {
      let url = graffiti.toDataURL('image/png');
      let a = document.createElement('a');
      a.href = url; a.download = 'graffiti.png';
      a.click();
    };
    document.getElementById('shareGraffitiBtn').onclick = function() {
      let url = graffiti.toDataURL('image/png');
      let qr = window.open();
      qr.document.write(`<img src='https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(url)}'>`);
    };
    document.getElementById('clearGraffitiBtn').onclick = function() {
      gctx.clearRect(0,0,graffiti.width,graffiti.height);
      saveGraffitiStep();
    };
    function saveGraffitiStep(){
      if(graffitiStep<graffitiHistory.length-1) graffitiHistory.length=graffitiStep+1;
      graffitiHistory.push(graffiti.toDataURL());
      if(graffitiHistory.length>30) graffitiHistory.shift();
      graffitiStep = graffitiHistory.length-1;
    }
    function getBrushColor(now, speed, type) {
      if(type==='rainbow') return `hsl(${(now.x+now.y)%360},90%,${Math.max(60,120-speed*2)}%)`;
      if(type==='glow') return `rgba(80,180,255,${Math.max(0.2,1-speed/18)})`;
      if(type==='fire') return `rgba(${255},${Math.max(80,255-speed*8)},0,${Math.max(0.3,1-speed/10)})`;
      if(type==='star') return `rgba(255,255,255,${Math.max(0.2,1-speed/10)})`;
      if(type==='wave') return `hsl(${Date.now()/10%360},80%,70%)`;
      return '#f97316';
    }
    function drawParticles(x,y,color){
      for(let i=0;i<3;i++){
        let px = x+Math.random()*16-8, py = y+Math.random()*16-8;
        gctx.beginPath();
        gctx.arc(px,py,Math.random()*3+1,0,2*Math.PI);
        gctx.fillStyle = color;
        gctx.globalAlpha = 0.5;
        gctx.fill();
        gctx.globalAlpha = 1;
      }
    }

    // ====== 粒子沙盒 ======
    const particleCanvas = document.getElementById('particleCanvas');
    const pctx = particleCanvas.getContext('2d');
    let mode = 'gravity';
    let particles = [];
    let particleCount = 18;
    let particleSize = 8;
    let particleMass = 3;
    let springs = [];
    document.getElementById('particleCountSlider').oninput = function(){
      particleCount = parseInt(this.value);
      document.getElementById('particleCountLabel').textContent = particleCount+'粒子';
      resetParticles();
    };
    document.getElementById('particleSizeSlider').oninput = function(){
      particleSize = parseInt(this.value);
      document.getElementById('particleSizeLabel').textContent = particleSize+'像素';
      resetParticles();
    };
    document.getElementById('particleMassSlider').oninput = function(){
      particleMass = parseInt(this.value);
      document.getElementById('particleMassLabel').textContent = '质量'+particleMass;
      resetParticles();
    };
    document.getElementById('gravityBtn').onclick = ()=>{mode='gravity';};
    document.getElementById('repelBtn').onclick = ()=>{mode='repel';};
    document.getElementById('elasticBtn').onclick = ()=>{mode='elastic';};
    document.getElementById('attractBtn').onclick = ()=>{mode='attract';};
    document.getElementById('explodeBtn').onclick = ()=>{explodeParticles();};
    document.getElementById('resetParticleBtn').onclick = ()=>{resetParticles();};
    document.getElementById('springBtn').onclick = ()=>{
      mode='spring';
      springs = [];
      for(let i=0;i<particles.length-1;i++){
        springs.push({a:i, b:i+1, rest:40, k:0.05});
      }
      showAchievement('已切换到弹簧链模式！');
    };
    document.getElementById('blackholeBtn').onclick = ()=>{
      mode='blackhole';
      showAchievement('已切换到黑洞模式！');
    };
    function resetParticles() {
      particles = Array.from({length: particleCount},()=>({
        x:Math.random()*particleCanvas.width,
        y:Math.random()*particleCanvas.height,
        vx: (Math.random()-0.5)*2,
        vy: (Math.random()-0.5)*2,
        c: `hsl(${Math.random()*360},80%,60%)`,
        size: particleSize,
        mass: particleMass
      }));
    }
    function explodeParticles() {
      for(let p of particles){
        p.vx = (Math.random()-0.5)*8;
        p.vy = (Math.random()-0.5)*8;
      }
    }
    function drawParticlesBox() {
      pctx.clearRect(0,0,particleCanvas.width,particleCanvas.height);
      for(let i=0;i<particles.length;i++){
        let p=particles[i];
        // 弹簧链
        if(mode==='spring'){
          springs.forEach(s=>{
            if(s.a===i){
              let q=particles[s.b];
              let dx=q.x-p.x, dy=q.y-p.y, dist=Math.sqrt(dx*dx+dy*dy);
              let force = s.k*(dist-s.rest);
              p.vx += force*dx/dist; p.vy += force*dy/dist;
              q.vx -= force*dx/dist; q.vy -= force*dy/dist;
            }
          });
        }
        // 黑洞
        if(mode==='blackhole'){
          let dx=particleCanvas.width/2-p.x, dy=particleCanvas.height/2-p.y, dist=Math.sqrt(dx*dx+dy*dy);
          let force = 0.2/(dist*dist+1);
          p.vx += force*dx; p.vy += force*dy;
        }
        for(let j=0;j<particles.length;j++){
          if(i===j) continue;
          let q=particles[j];
          let dx=q.x-p.x,dy=q.y-p.y,dist=Math.sqrt(dx*dx+dy*dy);
          if(dist<1) dist=1;
          let force = 0;
          if(mode==='gravity') force = 0.08/dist;
          if(mode==='repel') force = -0.08/dist;
          if(mode==='elastic') force = Math.sin(Date.now()/500)/dist*0.12;
          if(mode==='attract') force = 0.15/(dist*dist);
          p.vx += force*dx; p.vy += force*dy;
        }
        p.x += p.vx; p.y += p.vy;
        if(p.x<0||p.x>particleCanvas.width) p.vx*=-0.8;
        if(p.y<0||p.y>particleCanvas.height) p.vy*=-0.8;
        p.x = Math.max(0,Math.min(p.x,particleCanvas.width));
        p.y = Math.max(0,Math.min(p.y,particleCanvas.height));
        pctx.beginPath();
        pctx.arc(p.x,p.y,p.size,0,2*Math.PI);
        pctx.fillStyle=p.c;
        pctx.shadowColor=p.c;
        pctx.shadowBlur=10;
        pctx.fill();
        pctx.shadowBlur=0;
      }
      requestAnimationFrame(drawParticlesBox);
    }
    // 互动玩法
    particleCanvas.addEventListener('pointerdown', e=>{
      let rect = particleCanvas.getBoundingClientRect();
      let x = e.clientX-rect.left, y = e.clientY-rect.top;
      for(let p of particles){
        let d = Math.sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y));
        if(d<16){
          p.vx += (Math.random()-0.5)*6;
          p.vy += (Math.random()-0.5)*6;
        }
      }
    });
    // 初始化
    graffiti.width = graffiti.offsetWidth; graffiti.height = graffiti.offsetHeight;
    particleCanvas.width = particleCanvas.offsetWidth; particleCanvas.height = particleCanvas.offsetHeight;
    resetParticles();
    drawParticlesBox();

    // ====== AI智能推荐 ======
    document.getElementById('aiSuggestBtn').onclick = function() {
      // 推荐未发现的组合
      let keys = Object.keys(formulas).filter(k=>!collection[k]);
      if(keys.length){
        let key = keys[Math.floor(Math.random()*keys.length)];
        let [a,b] = key.split('+');
        let aBtn = Array.from(document.querySelectorAll('.element-btn')).find(btn=>btn.dataset.ele===a);
        let bBtn = Array.from(document.querySelectorAll('.element-btn')).find(btn=>btn.dataset.ele===b);
        aBtn.click(); setTimeout(()=>bBtn.click(), 200);
        showAchievement('AI为你推荐了一个新组合，快去探索吧！');
      }else{
        showAchievement('你已发现全部组合，太厉害了！');
      }
    };

    // ====== AI物理模式 ======
    document.getElementById('aiParticleBtn').onclick = function() {
      // AI自动切换物理模式
      let modes = ['gravity','repel','elastic','attract'];
      let idx = Math.floor(Math.random()*modes.length);
      mode = modes[idx];
      showAchievement('AI已切换到 "'+mode+'" 模式！');
    };

    // ====== AI助手浮动按钮 ======
    document.getElementById('aiHelperBtn').onclick = function() {
      alert('我是AI助手，可以为你解答玩法、成就、彩蛋等问题，或给你探索建议！');
    };
  </script>
</body>
</html> 